package com.tmobile.books.matmadavinci;

import java.util.ArrayList;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.tmobile.books.matmadavinci.database.Book;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;

public class MainActivity extends FragmentActivity {

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private static final String TAG = "MainActivity";
	private static ArrayList<Book> chapterContent; 
	private SharedPreferences mPref;
	private Editor editor;
	private static float fontSize;
	private int bookmarkedSpine, selectedSpine;
	View backPressedView, layoutView;
	PopupWindow backPressedPopup;
	boolean showRatePopup = true;
	TestFragmentAdapter mAdapter;
	ViewPager mPager;
	PageIndicator mIndicator;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		layoutView = findViewById(R.id.drawer_layout);
		backPressedView = getLayoutInflater().inflate(
				R.layout.back_pressed_popup, null);
		chapterContent = AppSingleton.getInstance().getListBooks();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		mPref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		editor = mPref.edit();
		fontSize = mPref.getFloat(Constants.PREF_FONT_SIZE, 16);
		// Set the adapter for the list view
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, Constants.listMenu));
		// Set the list's click listener
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {

			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				super.onDrawerClosed(view);
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		// Set the drawer toggle as the DrawerListener
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		// mDrawerLayout.openDrawer(Gravity.LEFT);
		mAdapter = new TestFragmentAdapter(getSupportFragmentManager(),
				getApplicationContext());

		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);

		mIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
		mIndicator.setViewPager(mPager);
		mPager.setOffscreenPageLimit(1);
		if (savedInstanceState == null) {
			bookmarkedSpine = mPref.getInt(Constants.PREF_BOOKMARK_SPINE, 0);
			selectViewPagerIndicator(bookmarkedSpine);
		}
		mIndicator
				.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						selectedSpine = position;
					}

					@Override
					public void onPageScrolled(int position,
							float positionOffset, int positionOffsetPixels) {
					}

					@Override
					public void onPageScrollStateChanged(int state) {
					}
				});
	}

	@Override
	protected void onPause() {
		// tu dong bookmark
		editor.putInt(Constants.PREF_BOOKMARK_SPINE, selectedSpine);
		editor.commit();
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * chon index cua viewpager
	 * 
	 * @param viewpagerIndex
	 */
	private void selectViewPagerIndicator(int viewpagerIndex) {
		mPager.setCurrentItem(viewpagerIndex, true);
		selectedSpine = viewpagerIndex;
	}

	private void gotoAppOnStore() {
		final String appPackageName = getPackageName();
		// getPackageName() from Context or Activity object
		try {
			startActivity(new Intent(Intent.ACTION_VIEW,
					Uri.parse("market://details?id=" + appPackageName)));
		} catch (ActivityNotFoundException anfe) {
			startActivity(new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://play.google.com/store/apps/details?id="
							+ appPackageName)));
		}
//		finish();
	}

	private void getMoreAppsOnStore() {
		// getPackageName() from Context or Activity object
		startActivity(new Intent(
				Intent.ACTION_VIEW,
				Uri.parse("https://play.google.com/store/apps/developer?id=grassbean")));
//		finish();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.increase_font).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		switch (item.getItemId()) {
		case R.id.increase_font:
			// create intent to perform web search for this planet
			fontSize += 2;
			editor.putFloat(Constants.PREF_FONT_SIZE, fontSize);
			editor.commit();
			mAdapter.notifyDataSetChanged();
			// define broadcast and send
			sendBroadcast(fontSize);
			//
			return true;

		case R.id.decrease_font:
			fontSize -= 2;
			editor.putFloat(Constants.PREF_FONT_SIZE, fontSize);
			editor.commit();
			// define broadcast and send
			sendBroadcast(fontSize);
			mAdapter.notifyDataSetChanged();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void sendBroadcast(float fontSize) {
		Intent intent = new Intent(Constants.BROADCAST_RECEIVER_KEY);
		// add data
		intent.putExtra(Constants.BROADCAST_MESSAGE_FONT_SIZE,
				String.valueOf(fontSize));
		// intent.setAction("de.vogella.android.mybroadcast");
		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
	}

	WebView webview;
	int i = 0;

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}

	/** Swaps fragments in the main content view */
	private void selectItem(int position) {
		// Create a new fragment and specify the chapter to show based on
		// position
		// neu position = 0 -> muc luc -> show Fragment Content
		// if (position == 0) {
		// fragment = new BookContentFragment();
		// } else {
		// fragment = new ChapterFragment();
		// }
		// Bundle args = new Bundle();
		// args.putInt(ChapterFragment.ARG_CHAPTER_NUMBER, position);
		// fragment.setArguments(args);
		// Insert the fragment by replacing any existing fragment
		// FragmentManager fragmentManager = getSupportFragmentManager();
		// fragmentManager.beginTransaction()
		// .replace(R.id.content_frame, fragment).commit();
		// Highlight the selected item, update the title, and close the
		// drawer
		// mDrawerList.setItemChecked(position, true);
		mDrawerLayout.closeDrawer(mDrawerList);
		// selectedSpine = position;
		switch (position) {
		case 0:
			getMoreAppsOnStore();
			break;

		case 1:
			gotoAppOnStore();
			break;
		default:
			break;
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

}
